package cn.b.sky.mes.andon.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.mes.andon.enums.ServiceTypeEnums;
import cn.b.sky.mes.andon.model.AndonEvent;
import cn.b.sky.mes.andon.model.AndonEventProcess;
import cn.b.sky.mes.andon.model.condition.AndonEventCondition;
import cn.b.sky.mes.andon.service.AndonEventProcessService;
import cn.b.sky.mes.andon.service.AndonEventService;
import cn.b.sky.shop.activiti.model.SkyService;
import cn.b.sky.shop.activiti.model.condition.SkyServiceCondition;
import cn.b.sky.shop.activiti.service.SkyServiceService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;

/**
 * <strong>Title : AndonEventController.java<br>
 * </strong> <strong>Package : cn.b.sky.mes.andon.controller<br>
 * </strong> <strong>Description : </strong>Andon事件定义Controller<br>
 * <strong>Create on : 2016年10月14日 下午5:59:47<br>
 * </strong>
 * <p>
 * 
 * @author ShiYing.Ke<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 *          <strong>修改历史:</strong><br>
 *          修改人|修改日期|修改描述<br>
 *          -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping("/andonEvent/*")
public class AndonEventController extends SecurityController {

	@Autowired
	AndonEventService andonEventService;
	
	@Autowired
	AndonEventProcessService andonEventProcessService;

	@Autowired
	SkyServiceService skyServiceService;

	@RequestMapping("list")
	public String list(Model model,
			@ModelAttribute("condition") AndonEventCondition condition,
			String navTabId) {
		condition.setSiteCode(getSiteCode());
		List<AndonEvent> list = this.andonEventService
				.selectAndonEventListByCondition(condition);
		condition.setData(list);
		int total = this.andonEventService
				.selectAndonEventTotalCount(condition);
		condition.setTotalCount(total);
		model.addAttribute(NAVTABID, navTabId);
		model.addAttribute("page", condition);
		return "andon/andonEvent/andonEvent_list";
	}
	
	@RequestMapping(value = "lookUp")
  public String lookUp(Model model,
      @ModelAttribute("condition") AndonEventCondition condition,
      String navTabId) {
    condition.setSiteCode(getSiteCode());
    List<AndonEvent> list = this.andonEventService
        .selectAndonEventListByCondition(condition);
    condition.setData(list);
    int total = this.andonEventService
        .selectAndonEventTotalCount(condition);
    condition.setTotalCount(total);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("page", condition);
    return "andon/andonEvent/andonEvent_lookup";
  }

	@RequestMapping("add")
	public String add(String navTabId, Model model) {
		model.addAttribute(NAVTABID, navTabId);
		List<SkyService> list = getSkyServiceList();
		model.addAttribute("serviceList", list);
		return "andon/andonEvent/andonEvent_add";
	}

	private List<SkyService> getSkyServiceList() {
		SkyServiceCondition imeCon = new SkyServiceCondition();
		imeCon.setEndRow(-1);
		imeCon.setType(ServiceTypeEnums.EVENT.getValue());
		List<SkyService> list = skyServiceService.getService(imeCon);
		return list;
	}

	@RequestMapping("modify")
	public String modify(String navTabId, Model model, String code) {
		model.addAttribute(NAVTABID, navTabId);
		List<SkyService> list = getSkyServiceList();
		model.addAttribute("serviceList", list);
		AndonEvent andonEvent = andonEventService.selectAndonEvent(
				this.getSiteCode(), code);
		model.addAttribute("andonEvent", andonEvent);
		model.addAttribute("pattern", "modify");
		return "andon/andonEvent/andonEvent_add";
	}

	@RequestMapping("view")
	public String view(String navTabId, Model model, String code) {
		model.addAttribute(NAVTABID, navTabId);
		List<SkyService> list = getSkyServiceList();
		model.addAttribute("serviceList", list);
		AndonEvent andonEvent = andonEventService.selectAndonEvent(
				this.getSiteCode(), code);
		model.addAttribute("andonEvent", andonEvent);
		return "andon/andonEvent/andonEvent_view";
	}

	@RequestMapping("validate")
	@ResponseBody
	public boolean validate(String eventCode) {
		if (StringUtils.isBlank(eventCode)) {
			return true;
		} else {
			AndonEvent andonEvent = andonEventService.selectAndonEvent(
					this.getSiteCode(), eventCode);
			return andonEvent == null;
		}
	}

	@RequestMapping("save")
	@ResponseBody
	public DWZResult save(String id, String ids, AndonEvent andonEvent,
			String navTabId, Model model) {
		if (null == andonEvent) {
			return ajaxError(getImeViewMessageI18n(null,
					SystemConstant.PARAMETERNULL));
		}
		andonEvent.setSiteCode(this.getSiteCode());
		// 关联的流程定义
		List<AndonEventProcess> list = new ArrayList<AndonEventProcess>();
		if(StringUtils.isNotEmpty(ids)){
			String[] idArr = ids.split(",");
			for (int i = 0; i < idArr.length; i++) {
				AndonEventProcess aep = new AndonEventProcess();
				aep.setSiteCode(this.getSiteCode());
				aep.setProcessID(idArr[i]);
				aep.setEventCode(andonEvent.getEventCode());
				setCreateInfo(aep);
				list.add(aep);
			}
		}
		andonEvent.setAndonEventProcessList(list);
		if (StringUtils.isBlank(id)) {
			setCreateInfo(andonEvent);
			andonEventService.saveAndonEvent(andonEvent);
		} else {
			setModifyInfo(andonEvent);
			andonEventService.updateAndonEvent(andonEvent);
		}
		return dialogAjaxDone(
				getImeViewMessageI18n(null, "successfulOperation.M"), navTabId,
				null, null, null);
	}

	@RequestMapping("delete")
	@ResponseBody
	public DWZResult delete(String navTabId, Model model, String codes,
			HttpServletRequest request) {
		String[] idArr = codes.split(",");
		List<BatchJobReport> reports = new ArrayList<BatchJobReport>();
		int failures = 0;
		for (int i = 0; i < idArr.length; i++) {
			String code = idArr[i];
			String message = null;
			message = andonEventService.deleteAndonEvent(this.getSiteCode(),
					code);
			boolean flag = true;
			if (!StringUtils.isBlank(message)) {
				failures += 1;
				flag = false;
				message = getImeViewMessageI18n(
						SecurityContextUtil.getLanguageCode(), message);
			}
			BatchJobReport report = new BatchJobReport(idArr[i], message, flag);
			reports.add(report);
		}
		if (failures == 0) {
			return navTabAjaxDone(
					navTabId,
					null,
					null,
					null,
					getImeViewMessageI18n(this.getCurrentLanguage(),
							"successfulOperation.M"), null);
		} else {
			return batchjobAjaxDone(request, reports);
		}
	}

	@RequestMapping("getEventProcessByServiceId")
	@ResponseBody
	public DWZResult getEventProcessByServiceId(String serviceId, String eventCode) {
		if (StringUtils.isBlank(serviceId)) {
			return ajaxError(getImeViewMessageI18n(
					SecurityContextUtil.getLanguageCode(),
					SystemConstant.PARAMETERNULL));
		}
		Long sid = Long.parseLong(serviceId);
		List<Map<String, Object>> processes = andonEventProcessService.selectRelAndonEventProcessByServiceId(sid);
		if(!CollectionUtils.isEmpty(processes) && StringUtils.isNotEmpty(eventCode)){
			for(Map<String, Object> m : processes){
				AndonEventProcess aep = new AndonEventProcess();
				aep.setSiteCode(this.getSiteCode());
				aep.setEventCode(eventCode);
				aep.setProcessID(m.get("KEY").toString());
				if(null != andonEventProcessService.selectAndonEventProcess(aep)){
					m.put("CHECKED", "checked");
				}
			}
		}
		return ajaxDone(processes);
	}

}
